package city.spring.modules.sitting.controller;

import city.spring.modules.oldman.entity.OldmanInfoEntity;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.sitting.entity.VisitRecordEntity;
import city.spring.modules.sitting.query.VisitRecordQuery;
import city.spring.modules.sitting.service.VisitRecordService;
import city.spring.modules.sitting.vo.VisitRecordInfoVO;
import city.spring.modules.sitting.vo.VisitRecordListVO;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import city.spring.utils.BeanUtils;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：巡诊记录
 *
 * @author 侯坤林
 * @date 2020-07-22 14:38:10
 */
@RestController
@RequestMapping("/visit_record")
public class VisitRecordController extends ApiController {
    private final VisitRecordService visitRecordService;
    private final UserService userService;
    private final OldmanInfoService oldmanInfoService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<VisitRecordEntity, ?>> entityOrderFields;

    public VisitRecordController(VisitRecordService visitRecordService, UserService userService, OldmanInfoService oldmanInfoService) {
        this.visitRecordService = visitRecordService;
        this.userService = userService;
        this.oldmanInfoService = oldmanInfoService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(VisitRecordEntity::getId);
        entityOrderFields.add(VisitRecordEntity::getUserId);
        entityOrderFields.add(VisitRecordEntity::getOldmanId);
        entityOrderFields.add(VisitRecordEntity::getDate);
        entityOrderFields.add(VisitRecordEntity::getBodyTemp);
        entityOrderFields.add(VisitRecordEntity::getPulsRate);
        entityOrderFields.add(VisitRecordEntity::getLeftBloodPressure1);
        entityOrderFields.add(VisitRecordEntity::getLeftBloodPressure2);
        entityOrderFields.add(VisitRecordEntity::getRightBloodPressure1);
        entityOrderFields.add(VisitRecordEntity::getRightBloodPressure2);
        entityOrderFields.add(VisitRecordEntity::getBreathRate);
        entityOrderFields.add(VisitRecordEntity::getBloodOxygenSaturation);
        entityOrderFields.add(VisitRecordEntity::getDiet);
        entityOrderFields.add(VisitRecordEntity::getSleepStatus);
        entityOrderFields.add(VisitRecordEntity::getExerciseStatus);
        entityOrderFields.add(VisitRecordEntity::getTowStoolStatus);
        entityOrderFields.add(VisitRecordEntity::getMentalStatus);
        entityOrderFields.add(VisitRecordEntity::getSee);
        entityOrderFields.add(VisitRecordEntity::getGmtCreated);
        entityOrderFields.add(VisitRecordEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>巡诊记录</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, VisitRecordQuery query) {
        LambdaQueryChainWrapper<VisitRecordEntity> lambdaQuery = buildLambdaQuery(query);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>巡诊记录</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, VisitRecordQuery query) {
        LambdaQueryChainWrapper<VisitRecordEntity> lambdaQuery = buildLambdaQuery(query);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<VisitRecordEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        List<VisitRecordEntity> records = page.getRecords();
        Map<String, UserEntity> users = userService.listByIds(records, VisitRecordEntity::getUserId, UserEntity::getId);
        Map<String, OldmanInfoEntity> oldmans = oldmanInfoService.listByIds(records, VisitRecordEntity::getOldmanId, OldmanInfoEntity::getId);

        OldmanInfoEntity oldmanInfoEntity = new OldmanInfoEntity();
        oldmanInfoEntity.setOldmanName("<找不到老人>");
        UserEntity userEntity = new UserEntity();
        userEntity.setNickname("<找不到医生>");
        List<VisitRecordListVO> results = records.stream().map(recordEntity -> {

            VisitRecordListVO vo = new VisitRecordListVO();
            vo.setId(recordEntity.getId());
            vo.setOldmanId(recordEntity.getOldmanId());
            vo.setOldmanName(oldmans.getOrDefault(recordEntity.getOldmanId(), oldmanInfoEntity).getOldmanName());
            vo.setOldmanBed("");
            vo.setUserId(recordEntity.getUserId());
            vo.setUserName(users.getOrDefault(recordEntity.getUserId(), userEntity).getNickname());
            vo.setDate(recordEntity.getDate());
            vo.setGmtCreated(Date.from(recordEntity.getGmtCreated().toInstant(ZoneOffset.UTC)));
            vo.setGmtModified(recordEntity.getGmtModified());
            return vo;
        }).collect(Collectors.toList());
        Page<VisitRecordListVO> page1 = new Page<>(page.getCurrent(), page.getSize(), page.getTotal(), page.isSearchCount());
        page1.setRecords(results);
        return success(page1);
    }

    /**
     * 获取一个 <strong>巡诊记录</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        VisitRecordEntity entity = visitRecordService.getById(id);
        if (entity == null) {
            return success(null);
        }
        VisitRecordInfoVO vo = BeanUtils.toChildren(entity, VisitRecordInfoVO.class);
        OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(vo.getOldmanId());
        if (oldmanInfoEntity != null) {
            vo.setOldmanName(oldmanInfoEntity.getOldmanName());
        }
        UserEntity userEntity = userService.getById(vo.getUserId());
        if (userEntity != null) {
            vo.setUserName(userEntity.getNickname());
        }
        return success(vo);
    }

    /**
     * 添加一个 <strong>巡诊记录</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody VisitRecordEntity entity) {
        visitRecordService.saveVisitRecord(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>巡诊记录</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody VisitRecordEntity entity) {
        entity.setId(id);
        visitRecordService.updateVisitRecord(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>巡诊记录</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        visitRecordService.deleteVisitRecord(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>巡诊记录</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        visitRecordService.deleteVisitRecord(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<VisitRecordEntity> buildLambdaQuery(VisitRecordQuery query) {
        LambdaQueryChainWrapper<VisitRecordEntity> lambdaQuery = visitRecordService.lambdaQuery();
        // 查询医生
        if (StringUtils.isNotBlank(query.getUserName())) {
            Set<String> userIdSet = userService.lambdaQuery().like(UserEntity::getNickname, query.getUserName()).list().stream().map(UserEntity::getId).collect(Collectors.toSet());
            if (userIdSet.isEmpty()) {
                userIdSet.add(null);
            }
            lambdaQuery.in(VisitRecordEntity::getUserId, userIdSet);
        }
        // 查询老人
        if (StringUtils.isNotBlank(query.getOldmanName())) {
            Set<String> oldmanIdSet = oldmanInfoService.lambdaQuery().like(OldmanInfoEntity::getOldmanName, query.getOldmanName()).list().stream().map(OldmanInfoEntity::getId).collect(Collectors.toSet());
            if (oldmanIdSet.isEmpty()) {
                oldmanIdSet.add(null);
            }
            lambdaQuery.in(VisitRecordEntity::getOldmanId, oldmanIdSet);
        }
        // 查询某个时间范围
        if (ArrayUtils.isNotEmpty(query.getDate()) && query.getDate().length == 2) {
            lambdaQuery.gt(VisitRecordEntity::getDate, query.getDate()[0]);
            lambdaQuery.lt(VisitRecordEntity::getDate, query.getDate()[1]);
        }
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<VisitRecordEntity> buildQuery(VisitRecordEntity entity) {
        QueryWrapper<VisitRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanId()), "oldman_id", entity.getOldmanId());
        wrapper.eq(entity.getDate() != null, "date", entity.getDate());
        wrapper.eq(entity.getBodyTemp() != null, "body_temp", entity.getBodyTemp());
        wrapper.eq(entity.getPulsRate() != null, "puls_rate", entity.getPulsRate());
        wrapper.eq(entity.getLeftBloodPressure1() != null, "left_blood_pressure1", entity.getLeftBloodPressure1());
        wrapper.eq(entity.getLeftBloodPressure2() != null, "left_blood_pressure2", entity.getLeftBloodPressure2());
        wrapper.eq(entity.getRightBloodPressure1() != null, "right_blood_pressure1", entity.getRightBloodPressure1());
        wrapper.eq(entity.getRightBloodPressure2() != null, "right_blood_pressure2", entity.getRightBloodPressure2());
        wrapper.eq(entity.getBreathRate() != null, "breath_rate", entity.getBreathRate());
        wrapper.eq(entity.getBloodOxygenSaturation() != null, "blood_oxygen_saturation", entity.getBloodOxygenSaturation());
        wrapper.like(StringUtils.isNotBlank(entity.getDiet()), "diet", entity.getDiet());
        wrapper.like(StringUtils.isNotBlank(entity.getSleepStatus()), "sleep_status", entity.getSleepStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getExerciseStatus()), "exercise_status", entity.getExerciseStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getTowStoolStatus()), "tow_stool_status", entity.getTowStoolStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getMentalStatus()), "mental_status", entity.getMentalStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getSee()), "see", entity.getSee());
        wrapper.eq(entity.getGmtCreated() != null, "gmt_created", entity.getGmtCreated());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

}
